package org.example.fronted.controller;


import com.alibaba.fastjson.JSON;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import org.apache.http.HttpResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.example.fronted.service.ShowOrderService;
import org.example.fronted.utils.utils.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;

import static com.google.zxing.client.j2se.MatrixToImageWriter.toBufferedImage;

@CrossOrigin("*")
@Controller
public class PaymentController {

    private ShowOrderService showOrderService;

    public PaymentController(ShowOrderService showOrderService) {
        this.showOrderService = showOrderService;
    }

    /***
     * 生成订单，统一下单，并且返回code_url
     * 微信支付接口  预下单返回 code_url
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping("/wxPay")
//    @ResponseBody
    public void wxPay(HttpServletRequest request, WeChatParams weChatParams, HttpServletResponse response) throws IOException {

        if (true) {

        }


        try {
            /**
             * 账号信息
             */
            String appid = "wx632c8f211f8122c6";//微信服务号的appid
            String mch_id = "1497984412"; //微信支付商户号
            String key = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC"; // 微信支付的API密钥
            String notify_url = "http://hello.free.idcfengye.com/notify_url";//回调地址【注意，这里必须要使用外网的地址】
            String ufdoder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";//微信下单API地址
            String trade_type = "NATIVE"; //类型【网页扫码支付】

            /**
             * 时间字符串
             */

            String oNo = request.getParameter("oNo");
            String price = request.getParameter("price");

            System.out.println("oNo========" + oNo);
            System.out.println("price========" + price);
            //初始化数据
//            weChatParams.setBody("aaa");
//            weChatParams.setTotal_fee("1");

//            Random random = new Random(5);
//            int i = random.nextInt(100);
            String time = String.valueOf(System.currentTimeMillis());

//            weChatParams.setOut_trade_no(time);
//            weChatParams.setAttach(price);
//            weChatParams.setMemberid("888");
//            getCodeUrl(response,weChatParams);

//            Cookie cookie = new Cookie("price", price);
//            response.addCookie(cookie);

//            Cookie[] cookies = request.getCookies();
//            for (Cookie cookie2 : cookies) {
////                cookie2.getName()
//            }

            String currTime = PayForUtil.getCurrTime();
            String strTime = currTime.substring(8, currTime.length());
            String strRandom = PayForUtil.buildRandom(4) + "";
            String nonce_str = strTime + strRandom;
            TreeMap<String, Object> packageParams = new TreeMap<String, Object>();
            packageParams.put("appid", appid);
            packageParams.put("mch_id", mch_id);
            packageParams.put("nonce_str", nonce_str);//随机字符串
            packageParams.put("body", "aaaa");//支付的商品名称
            packageParams.put("out_trade_no", time + nonce_str);//商户订单号【备注：每次发起请求都需要随机的字符串，否则失败。】
            packageParams.put("total_fee", "1");//支付金额
            packageParams.put("spbill_create_ip", PayForUtil.localIp());//客户端主机
            packageParams.put("notify_url", notify_url);
            packageParams.put("trade_type", trade_type);
            packageParams.put("attach", oNo);//额外的参数【业务类型+会员ID+支付类型】
            String sign = PayForUtil.createSign("UTF-8", packageParams, key);  //获取签名
            packageParams.put("sign", sign);

            String requestXML = XMLUtilTest.createXML(packageParams);
            System.err.println("微信支付请求参数的报文" + requestXML);


            InputStream inputStream = XMLUtilTest.sendXmlDataByPost(ufdoder_url, requestXML).getEntity().getContent();

            String code_url = XMLUtilTest.getElementValue(inputStream, "code_url"); //获取二维码地址

            //生成二维码图片
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            Map hints = new HashMap();
            BitMatrix bitMatrix = null;

            System.out.println("hello");
            bitMatrix = multiFormatWriter.encode(code_url, BarcodeFormat.QR_CODE, 250, 250, hints);
            BufferedImage image = toBufferedImage(bitMatrix);

            request.getSession().setAttribute("imge", image);
            request.getSession().setAttribute("oNo", oNo);
            response.sendRedirect("/pay.jsp?price="+price+"&oNo="+oNo);
//                return "redirect:/pay.jsp";

        } catch (Exception e) {
            e.printStackTrace();
        }
//        return null;
    }


//
//    @GetMapping("/ada")
//    public static void getCodeUrl(HttpServletResponse response, WeChatParams ps) throws IOException {
//    }

    //解析xml
    public static String getElementValue(InputStream is, String key) {
        SAXReader reader = new SAXReader();
        Document document = null;
        try {
            document = reader.read(is);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();

        for (Element element : elementList) {
            System.out.println(element.getName() + ": " + element.getStringValue());
            if (key.equals(element.getName())) {
                return element.getStringValue();
            }
        }
        return null;
    }


    /**
     * pc端微信支付之后的回调方法
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @PostMapping(value = "/notify_url")
    public void notify_url(HttpServletRequest request, HttpServletResponse response) throws Exception {


        System.out.println("回调方法");
        //读取参数
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();

        //解析xml成map
        Map<String, String> m = new HashMap<String, String>();
        m = XMLUtil.doXMLParse(sb.toString());

        //过滤空 设置 TreeMap
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        Iterator<String> it = m.keySet().iterator();
        while (it.hasNext()) {
            String parameter = it.next();
            String parameterValue = m.get(parameter);

            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }
        // 微信支付的API密钥
//        String key = WeChatConfig.APIKEY; // key
        String key = "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC"; // key

        /*	        lg.info("微信支付返回回来的参数："+packageParams);    */
        //判断签名是否正确
        if (PayForUtil.isTenpaySign("UTF-8", packageParams, key)) {
            //------------------------------
            //处理业务开始
            //------------------------------
            String resXml = "";
            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                // 这里是支付成功
                //执行自己的业务逻辑开始
                String app_id = (String) packageParams.get("appid");
                String mch_id = (String) packageParams.get("mch_id");
                String openid = (String) packageParams.get("openid");
                String is_subscribe = (String) packageParams.get("is_subscribe");//是否关注公众号

                //附加参数【商标申请_0bda32824db44d6f9611f1047829fa3b_15460】--【业务类型_会员ID_订单号】
                String attach = (String) packageParams.get("attach");
                //商户订单号
                String out_trade_no = (String) packageParams.get("out_trade_no");
                //付款金额【以分为单位】
                String total_fee = (String) packageParams.get("total_fee");
                //微信生成的交易订单号
                String transaction_id = (String) packageParams.get("transaction_id");//微信支付订单号
                //支付完成时间
                String time_end = (String) packageParams.get("time_end");

                String oNo = (String)request.getSession().getAttribute("oNo");
                System.out.println("attach=============="+attach);
                showOrderService.update(attach);

                System.out.println("数据库修改成功");



                System.err.println("请求过来的参数=======================");


                System.err.println(attach);
                System.err.println(out_trade_no);
                System.err.println(total_fee);
                System.err.println(transaction_id);
                System.err.println(time_end);

                //通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                System.err.println("支付成功============================");
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";


            } else {
                //lg.info("支付失败,错误信息：" + packageParams.get("err_code"));
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
            }
            //------------------------------
            //处理业务完毕
            //------------------------------
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();

        } else {
            // lg.info("通知签名验证失败");
        }

    }


}
